package com.bbx.taxi.client.widget.Drag;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.bbx.taxi.client.Adapter.Chat.SearchCityAdapter;
import com.bbx.taxi.client.Adapter.City.CityAdapter;
import com.bbx.taxi.client.Bean.Line.CitiesBean.AppCitysBean;
import com.bbx.taxi.client.Bean.Line.CitiesBean.AppCitysBean.ChildCitysBeanX;
import com.bbx.taxi.client.Bean.Line.CitiesBean.AppCitysBean.ChildCitysBeanX.ToCitiesBean;
import com.bbx.taxi.client.Bean.Line.CitiesBean.AppCitysBean.ChildCitysBeanX.ToCitiesBean.ChildCitysBean;
import com.bbx.taxi.client.Bean.Value;
import com.bbx.taxi.client.DB.LineDB;
import com.bbx.taxi.client.MyApplication;
import com.bbx.taxi.client.MyApplication.OnLocationResultListener;
import com.bbx.taxi.client.R;
import com.bbx.taxi.client.Util.HistoricCityUtils;
import com.bbx.taxi.client.Util.RequestUtils;
import com.bbx.taxi.client.Util.ToCity2;
import com.yanxuwen.DensityUtil;
import com.yanxuwen.MyRecyclerview.MyBaseAdapter;
import com.yanxuwen.PinnedHeader.DividerItemDecoration;
import com.yanxuwen.PinnedHeader.HeaderRecyclerAndFooterWrapperAdapter;
import com.yanxuwen.PinnedHeader.IndexBar.widget.IndexBar;
import com.yanxuwen.PinnedHeader.ViewHolder;
import com.yanxuwen.PinnedHeader.suspension.SuspensionDecoration;
import com.yanxuwen.loadview.LoadingDialog;

import java.util.ArrayList;
import java.util.List;
/**
 * Created by Flavien Laurent (flavienlaurent.com) on 23/08/13.
 */
public class CityDragLayout extends BaseDragLayout  implements TextWatcher, MyApplication.EventHandler ,OnLocationResultListener{
	private  final String locationtitle="当前定位城市：";
	private  final String location_no="未定位";
	private LinearLayoutManager mManager;
	private SuspensionDecoration mDecoration;
	List<AppCitysBean> list_startcity=new ArrayList<>();
	List<ToCitiesBean> list_endcity=new ArrayList<>();
	public static final int SELECTCITY_RESULT_CODE=10;
	ImageButton mClearSearchBtn;
	 View mCityContainer;
	View mSearchContainer;
	RecyclerView mCityListView;
	IndexBar mIndexBar;
	ListView mSearchListView;
	TextView tv_nocity;
	private SearchCityAdapter mSearchCityAdapter;
	private CityAdapter mAdapter;
	private HeaderRecyclerAndFooterWrapperAdapter mHeaderAdapter;
	private LineDB db_line;// 线路数据库
	/**目的地或出发地*/
	private int intentType;
	private String start_address_name="";
	private boolean isSn=false;
	private boolean isStart=true;
	/**当前选择的城市*/
	private String currentCity="";
	public MyApplication mApplication;
	public LoadingDialog loaddialog;
	ImageView iv_city_delete;
	public int Location_length=-1;
	/**
	 * 显示指示器DialogText
	 */
	private TextView mTvSideBarHint;
	/**
	 * 该拖动试图的开关状态
	 * 
	 */
	public interface OnCityDragViewStatusListener {
		/** 该拖动试图的开关状态 */
		public void onDragViewStatus(boolean isOpen);
		/** 该拖动试图的点击城市监听 */
		public void onClickCity(String city,String is_detail);
	};

	public OnCityDragViewStatusListener mOnCityDragViewStatusListener;

	public void setOnCityDragViewStatusListener(OnCityDragViewStatusListener l) {
		mOnCityDragViewStatusListener = l;
	};


	public CityDragLayout(Context context) {
		super(context);
	}

	public CityDragLayout(Context context, AttributeSet attrs) {
		super(context, attrs, 0);
	}

	public CityDragLayout(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	@Override
	public void initView() {
		mApplication=MyApplication.getInstance();
		loaddialog = new LoadingDialog(context, true,Value.LOADDIALOGTIME);
		setContentView(findViewById(R.id.desc));
		mClearSearchBtn=(ImageButton)getContentView().findViewById(R.id.ib_clear_text);
		mCityContainer=(View)getContentView().findViewById(R.id.city_content_container);
		mSearchContainer=(View)getContentView().findViewById(R.id.search_content_container);
		mCityListView=(RecyclerView)getContentView().findViewById(R.id.citys_list);
		mIndexBar=(IndexBar)getContentView().findViewById(R.id.indexBar);
		mSearchListView=(ListView)getContentView().findViewById(R.id.search_list);
		tv_nocity=(TextView)findViewById(R.id.tv_nocity);
		//使用indexBar
		mTvSideBarHint = (TextView) getContentView().findViewById(R.id.tvSideBarHint);//HintTextView
		mIndexBar = (IndexBar) findViewById(R.id.indexBar);//IndexBar

		mCityListView.setLayoutManager(mManager = new LinearLayoutManager(context));
	}
	@SuppressLint("NewApi")
	public void initAdapter(){
		if(mAdapter==null) {
			mAdapter = new CityAdapter(context,isStart, list_startcity,list_endcity, 1);
			mHeaderAdapter = new HeaderRecyclerAndFooterWrapperAdapter(mAdapter) {
				@Override
				protected void onBindHeaderHolder(ViewHolder holder, int headerPos, int layoutId, final Object o) {
					final String city = (String) o;
					holder.setText(R.id.tvCity, city);
					if (city != null && !city.equals("") && !city.contains(location_no)) {
						holder.setOnClickListener(R.id.content, new OnClickListener() {
							@Override
							public void onClick(View v) {
								String detail = Value.CITY_NODETAIL;
								//如果含有“当前定位城市”标题，则裁剪掉
								mOnCityDragViewStatusListener.onClickCity(city.replace(locationtitle, ""), detail);
							}
						});
					}
				}
			};
			//显示头部：定位城市
			String locationcity=mApplication.getLoctionCity(isSn);
			if(locationcity==null||locationcity.equals("")){
				locationcity=location_no;
			}else{
				locationcity=locationtitle+locationcity;
			}
			mHeaderAdapter.addHeaderView(R.layout.listitem_select_city, locationcity);
			mCityListView.setAdapter(mHeaderAdapter);
			mCityListView.addItemDecoration(mDecoration = new SuspensionDecoration(context, isStart ? list_startcity : list_endcity).setHeaderViewCount(mHeaderAdapter.getHeaderViewCount()));
			mDecoration.setTitleFontSize(DensityUtil.dip2px(context, 12));
			mDecoration.setColorTitleBg(context.getColor(R.color.background2));
			//如果add两个，那么按照先后顺序，依次渲染。
			mCityListView.addItemDecoration(new DividerItemDecoration(context, LinearLayoutManager.VERTICAL));
			mIndexBar.setPressedShowTextView(mTvSideBarHint)//设置HintTextView
					.setNeedRealIndex(true)//设置需要真实的索引
					.setLayoutManager(mManager);//设置RecyclerView的LayoutManager
			mAdapter.setOnItemClickListener(new MyBaseAdapter.OnItemClickListener() {
				@Override
				public void onItemClick(MyBaseAdapter.BaseViewHolder holder, View view, int position) {
					//出发地
					if (isStart) {
						if (list_startcity == null || list_startcity.isEmpty()) return;
						List<ChildCitysBeanX> list_startchildcity = list_startcity.get(position).getChild_citys();
						//子类不为空
						//如果子类只有一个，且子类跟父类名字一样，则不展开直接选中
						if (list_startchildcity != null && !list_startchildcity.isEmpty())
							if (list_startchildcity.size() == 1 && list_startchildcity.get(0).getName().equals(list_startcity.get(position).getName())) {
								final String name = list_startchildcity.get(0).getName();
								final String detail = list_startchildcity.get(0).getIs_detail();
								onItemClickParent(holder, name, detail);

							} else {
								final CityAdapter.ViewHolder mViewHolder = (CityAdapter.ViewHolder) holder;
								if (!holder.isExpanded()) {
									mViewHolder.expand_sign.postDelayed(new Runnable() {
										@Override
										public void run() {
											if (mAdapter.last_expand_sign != null) {
												mAdapter.last_expand_sign.setVisibility(GONE);
											}
											mViewHolder.expand_sign.setVisibility(VISIBLE);
											mAdapter.last_expand_sign = mViewHolder.expand_sign;
										}
									}, 50);
									mViewHolder.setChildData(holder, mOnCityDragViewStatusListener, list_startcity.get(position).getChild_citys(), null, getCurrentCity());
								} else {
									mViewHolder.expand_sign.postDelayed(new Runnable() {
										@Override
										public void run() {
											mViewHolder.expand_sign.setVisibility(GONE);
										}
									}, 50);
								}
								holder.expand();
							}
						//子类为空，则取父类
						else {
							final String name = list_startcity.get(position).getName();
							final String detail = Value.CITY_NODETAIL;
							onItemClickParent(holder,name,detail);
						}
					}
					//目的地
					else {
						if (list_endcity == null || list_endcity.isEmpty()) return;
						List<ChildCitysBean> list_endchildcity = list_endcity.get(position).getChild_citys();
						//子类不为空
						//如果子类只有一个，且子类跟父类名字一样，则不展开直接选中
						if (list_endchildcity != null && !list_endchildcity.isEmpty())
							if (list_endchildcity.size() == 1 && list_endchildcity.get(0).getName().equals(list_endcity.get(position).getName())) {
								final String name = list_endchildcity.get(0).getName();
								final String detail = list_endchildcity.get(0).getIs_detail();
								onItemClickParent(holder,name,detail);
							} else {
								final CityAdapter.ViewHolder mViewHolder = (CityAdapter.ViewHolder) holder;
								if (!holder.isExpanded()) {
									mViewHolder.expand_sign.postDelayed(new Runnable() {
										@Override
										public void run() {
											if (mAdapter.last_expand_sign != null) {
												mAdapter.last_expand_sign.setVisibility(GONE);
											}
											mViewHolder.expand_sign.setVisibility(VISIBLE);
											mAdapter.last_expand_sign = mViewHolder.expand_sign;
										}
									}, 50);
									mViewHolder.setChildData(holder, mOnCityDragViewStatusListener, null, list_endcity.get(position).getChild_citys(), getCurrentCity());
								} else {
									mViewHolder.expand_sign.postDelayed(new Runnable() {
										@Override
										public void run() {
											mViewHolder.expand_sign.setVisibility(GONE);
										}
									}, 50);
								}
								holder.expand();
							}
						//子类为空，则取父类
						else {
							final String name = list_endcity.get(position).getName();
							final String detail = Value.CITY_NODETAIL;
							onItemClickParent(holder,name,detail);
						}
					}
				}
			});

			mSearchListView
					.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {

						@Override
						public void onItemClick(AdapterView<?> parent, View view,
												int position, long id) {
							close();
							if (mOnCityDragViewStatusListener != null) {
								mOnCityDragViewStatusListener.onDragViewStatus(false);
								mOnCityDragViewStatusListener.onClickCity(mSearchCityAdapter.getCity(position), mSearchCityAdapter.getDetail(position));
							}
						}
					});
		}
	}

	/**
	 * @param holder
	 * @param name
	 * @param detail
	 * 点击父类，也就是不展开
	 */
	public void onItemClickParent(MyBaseAdapter.BaseViewHolder holder, final String name, final String detail){
		finish();
		mOnCityDragViewStatusListener.onClickCity(name, detail);
	}
	public void finish(){
		mAdapter.setExpandPostion(-1);
		if (mAdapter.last_expand_sign != null) {
			mAdapter.last_expand_sign.setVisibility(GONE);
		}
	}
	public void setData(){
		if(mAdapter!=null&&mHeaderAdapter!=null){
		//设置开通城市
		try{
			list_startcity.clear();
			list_startcity.addAll(mApplication.getStarCity(isSn));
		}catch (Exception e){}
		try{
			list_endcity.clear();
			list_endcity.addAll(mApplication.getEndCity(isSn));
		}catch (Exception e){}
		//读取历史城市,由于历史城市结构是String类型，所以要转换
		List<String> list_historic=new ArrayList<>();
		list_historic.addAll(HistoricCityUtils.onReadHistoricCity(context, isStart ? HistoricCityUtils.Type.start : HistoricCityUtils.Type.end, isSn));
		if(isStart){
			for(int i=0;i<list_historic.size();i++){
					AppCitysBean mAppCitysBean=new AppCitysBean();
					mAppCitysBean.setCity(list_historic.get(i));
					mAppCitysBean.setName(list_historic.get(i));
					mAppCitysBean.setProvince("");
					mAppCitysBean.setIsSn(isSn);
				    mAppCitysBean.setIsHistoric(true);
				    List<ChildCitysBeanX> list_startchildcity=new ArrayList<>();
					ChildCitysBeanX mChildCitysBeanX=new ChildCitysBeanX();
					mChildCitysBeanX.setCity(list_historic.get(i));
					mChildCitysBeanX.setName(list_historic.get(i));
				    mChildCitysBeanX.setIs_detail(Value.CITY_NODETAIL);
				    list_startchildcity.add(mChildCitysBeanX);
				    mAppCitysBean.setChild_citys(list_startchildcity);
					list_startcity.add(i,mAppCitysBean);
				}
		}else{
			for(int i=0;i<list_historic.size();i++){
					ToCitiesBean mToCitiesBean=new ToCitiesBean();
					mToCitiesBean.setCity(list_historic.get(i));
					mToCitiesBean.setName(list_historic.get(i));
					mToCitiesBean.setProvince("");
					mToCitiesBean.setIsSn(isSn);
				    mToCitiesBean.setIsHistoric(true);
				    List<ChildCitysBean> list_endchildcity=new ArrayList<>();
					ChildCitysBean mChildCitysBean=new ChildCitysBean();
					mChildCitysBean.setCity(list_historic.get(i));
					mChildCitysBean.setName(list_historic.get(i));
				    mChildCitysBean.setIs_detail(Value.CITY_NODETAIL);
					mChildCitysBean.setIsSn(isSn);
				    list_endchildcity.add(mChildCitysBean);
				    mToCitiesBean.setChild_citys(list_endchildcity);
				list_endcity.add(i,mToCitiesBean);
			}
		}
		mIndexBar
				.setSuspensionDecoration(mDecoration)
				.setNeedRealIndex(true)
				.setIsSort(isSn)
				.setIsShowIndex(isSn)
				.setSourceDatas(isStart ? list_startcity : list_endcity)//设置数据
				.setHeaderViewCount(mHeaderAdapter.getHeaderViewCount())//设置HeaderView数量
				.invalidate();

		mAdapter.setDatas(isStart ? list_startcity : list_endcity);
		mHeaderAdapter.notifyDataSetChanged();
			try{mCityListView.scrollToPosition(0);}catch (Exception e){}
		if((isStart?list_startcity:list_endcity).isEmpty()){
			mCityListView.setVisibility(View.GONE);
			tv_nocity.setVisibility(View.VISIBLE);
		}else {
			mCityListView.setVisibility(View.VISIBLE);
			tv_nocity.setVisibility(View.GONE);
		}
		}
	}
	@Override
	protected void onViewStatus(boolean isOpen){
		if(isOpen){
			initAdapter();
			initData();
			initData2();
		}else{
			finish();
//			//关闭的时候清空数据，不然展开动画会失效,如果数据太多会卡，则不能清空
//			if(list_endcity!=null)list_endcity.clear();
//			if(list_startcity!=null)list_startcity.clear();
//			mAdapter=null;
//			mHeaderAdapter=null;
		}
	}
	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		// do nothing
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		mSearchCityAdapter = new SearchCityAdapter(context,
				isStart?list_startcity: list_endcity,isStart);
		mSearchListView.setAdapter(mSearchCityAdapter);
		mSearchListView.setTextFilterEnabled(true);
		if ((isStart ?list_startcity:list_endcity).size() < 1 || TextUtils.isEmpty(s)) {
			mCityContainer.setVisibility(View.VISIBLE);
			mSearchContainer.setVisibility(View.INVISIBLE);
			mClearSearchBtn.setVisibility(View.GONE);
		} else {
			mClearSearchBtn.setVisibility(View.VISIBLE);
			mCityContainer.setVisibility(View.INVISIBLE);
			mSearchContainer.setVisibility(View.VISIBLE);
			mSearchCityAdapter.getFilter().filter(s);
		}
	}

	@Override
	public void afterTextChanged(Editable s) {
		if (!s.toString().isEmpty()) {
			iv_city_delete.setVisibility(View.VISIBLE);
		} else{
			iv_city_delete.setVisibility(View.GONE);
		}

	}
	@Override
	public void onCityComplite() {
		setData();
	}

	@Override
	public void onNetChange() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onLocationResult(BDLocation location) {
	}
	public void onLocationResult(ReverseGeoCodeResult result) {
	}
	@Override
	public void onLocationFail(boolean isnet) {
		// TODO Auto-generated method stub
		
	}
	/**
	 * 设置市内
	 */
	public void setIsSn(boolean isSn){
		this.isSn=isSn;
	}

	@Override
	public void close() {
		super.close();
	}

	public void setIsStart(boolean isStart){
		this.isStart=isStart;
	}
	public void setType(int intentType){
		this.intentType=intentType;
	}
	public void setCurrentCity(String currentCity){
		this.currentCity=currentCity;
	}
	public String getCurrentCity(){
		return currentCity!=null?currentCity:"";
	}
	public void setStartName(String start_address_name){
		this.start_address_name=start_address_name;
	}
	public void setaddTextChangedListener(EditText edittext,ImageView iv_city_delete){
		this.iv_city_delete=iv_city_delete;
		edittext.addTextChangedListener(this);
	}
	protected void initData2() {
		try{
		mApplication.setEventHandler(this);
		db_line=new LineDB();
		mSearchListView.setEmptyView(findViewById(R.id.search_empty));
		mSearchContainer.setVisibility(View.GONE);
		}catch(Exception e){}
	}
	protected void initData() {

		if(isSn){
			//出发地
			if(isStart){

			}
			//目的地
			else{
				List<ToCitiesBean> list_endcity =mApplication.getEndCity(isSn);
				if(list_endcity==null||list_endcity.isEmpty()){
					ToCity2.setEndCityList(context,"",isSn);
				}else{
					setData();
				}
			}
		}else{
			//出发地
			if(isStart){
				List<AppCitysBean> list_startcity=mApplication.getStarCity(isSn);
				if(list_startcity==null||list_startcity.isEmpty()){
					getOnLine();
				}else{
					setData();
				}
			}
			//目的地
			else{
				List<ToCitiesBean> list_endcity =mApplication.getEndCity(isSn);
				if(list_endcity==null||list_endcity.isEmpty()){
					getOnLine();
				}else{
					setData();
				}
			}
		}
	}
	/**
	 * 获取线路
	 */
	private void getOnLine() {
		RequestUtils.requestLinePlus((Activity)context, true);
	}
}
